# from flask import Flask, request, jsonify
# import sqlite3
#
# app = Flask(__name__)
#
#
# # 初始化数据库
# def init_db():
#     conn = sqlite3.connect('mahjong.db')
#     c = conn.cursor()
#     # 创建用户表
#     c.execute('''CREATE TABLE IF NOT EXISTS User (
#                     userId INTEGER PRIMARY KEY AUTOINCREMENT,
#                     username TEXT NOT NULL UNIQUE,
#                     password TEXT NOT NULL,
#                     email TEXT UNIQUE
#                 )''')
#     # 创建房间表
#     c.execute('''CREATE TABLE IF NOT EXISTS Room (
#                     roomId INTEGER PRIMARY KEY AUTOINCREMENT,
#                     creatorId INTEGER,
#                     roomName TEXT,
#                     FOREIGN KEY (creatorId) REFERENCES User(userId)
#                 )''')
#     # 创建用户房间关联表
#     c.execute('''CREATE TABLE IF NOT EXISTS UserRoom (
#                     userRoomId INTEGER PRIMARY KEY AUTOINCREMENT,
#                     userId INTEGER,
#                     roomId INTEGER,
#                     FOREIGN KEY (userId) REFERENCES User(userId),
#                     FOREIGN KEY (roomId) REFERENCES Room(roomId)
#                 )''')
#     # 创建对局表
#     c.execute('''CREATE TABLE IF NOT EXISTS Game (
#                     gameId INTEGER PRIMARY KEY AUTOINCREMENT,
#                     roomId INTEGER,
#                     gameStartTime TEXT DEFAULT CURRENT_TIMESTAMP,
#                     gameEndTime TEXT,
#                     FOREIGN KEY (roomId) REFERENCES Room(roomId)
#                 )''')
#     # 创建对局明细表
#     c.execute('''CREATE TABLE IF NOT EXISTS GameDetail (
#                     gameDetailId INTEGER PRIMARY KEY AUTOINCREMENT,
#                     gameId INTEGER,
#                     userId INTEGER,
#                     profitLoss REAL,
#                     FOREIGN KEY (gameId) REFERENCES Game(gameId),
#                     FOREIGN KEY (userId) REFERENCES User(userId)
#                 )''')
#     conn.commit()
#     conn.close()
#
#
# # 创建用户
# @app.route('/create_user', methods=['POST'])
# def create_user():
#     data = request.get_json()
#     username = data.get('username')
#     password = data.get('password')
#     email = data.get('email')
#     conn = sqlite3.connect('mahjong.db')
#     c = conn.cursor()
#     try:
#         c.execute("INSERT INTO User (username, password, email) VALUES (?,?,?)", (username, password, email))
#         conn.commit()
#         user_id = c.lastrowid
#         conn.close()
#         return jsonify({"message": "User created successfully", "userId": user_id})
#     except sqlite3.IntegrityError:
#         conn.close()
#         return jsonify({"message": "Username or email already exists"}), 400
#
#
# # 创建房间
# @app.route('/create_room', methods=['POST'])
# def create_room():
#     data = request.get_json()
#     creator_id = data.get('creatorId')
#     room_name = data.get('roomName')
#     conn = sqlite3.connect('mahjong.db')
#     c = conn.cursor()
#     c.execute("INSERT INTO Room (creatorId, roomName) VALUES (?,?)", (creator_id, room_name))
#     conn.commit()
#     room_id = c.lastrowid
#     conn.close()
#     return jsonify({"message": "Room created successfully", "roomId": room_id})
#
#
# # 加入房间
# @app.route('/join_room', methods=['POST'])
# def join_room():
#     data = request.get_json()
#     user_id = data.get('userId')
#     room_id = data.get('roomId')
#     conn = sqlite3.connect('mahjong.db')
#     c = conn.cursor()
#     c.execute("INSERT INTO UserRoom (userId, roomId) VALUES (?,?)", (user_id, room_id))
#     conn.commit()
#     user_room_id = c.lastrowid
#     conn.close()
#     return jsonify({"message": "Joined room successfully", "userRoomId": user_room_id})
#
#
# # 开始对局
# @app.route('/start_game', methods=['POST'])
# def start_game():
#     data = request.get_json()
#     room_id = data.get('roomId')
#     conn = sqlite3.connect('mahjong.db')
#     c = conn.cursor()
#     c.execute("INSERT INTO Game (roomId) VALUES (?)", (room_id,))
#     conn.commit()
#     game_id = c.lastrowid
#     conn.close()
#     return jsonify({"message": "Game started successfully", "gameId": game_id})
#
#
# # 结算本局
# @app.route('/settle_game', methods=['POST'])
# def settle_game():
#     data = request.get_json()
#     game_id = data.get('gameId')
#     details = data.get('details')  # 包含用户ID和盈亏分数的列表
#     conn = sqlite3.connect('mahjong.db')
#     c = conn.cursor()
#     for detail in details:
#         user_id = detail.get('userId')
#         profit_loss = detail.get('profitLoss')
#         c.execute("INSERT INTO GameDetail (gameId, userId, profitLoss) VALUES (?,?,?)", (game_id, user_id, profit_loss))
#     conn.commit()
#     # 更新对局结束时间
#     c.execute("UPDATE Game SET gameEndTime = CURRENT_TIMESTAMP WHERE gameId =?", (game_id,))
#     conn.commit()
#     conn.close()
#     return jsonify({"message": "Game settled successfully"})
#
#
# # 查看历史对局明细
# @app.route('/history_game_details/<int:game_id>', methods=['GET'])
# def history_game_details(game_id):
#     conn = sqlite3.connect('mahjong.db')
#     c = conn.cursor()
#     c.execute('''SELECT User.username, GameDetail.profitLoss
#                  FROM GameDetail
#                  JOIN User ON GameDetail.userId = User.userId
#                  WHERE GameDetail.gameId =?''', (game_id,))
#     results = c.fetchall()
#     details = []
#     for row in results:
#         details.append({
#             "username": row[0],
#             "profitLoss": row[1]
#         })
#     conn.close()
#     return jsonify({"gameId": game_id, "details": details})
#
#
# if __name__ == '__main__':
#     init_db()
#     app.run(debug=True)
